package com.study.zouchao.superproject.login.presenter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.login.contract.ILoginContract;
import com.study.zouchao.superproject.login.model.entity.User;
import com.study.zouchao.superproject.login.model.entity.result.LoginResult;
import com.study.zouchao.superproject.login.model.impl.LoginModel;
import com.study.zouchao.superproject.logininterceptor.LoginCarrier;
import com.study.zouchao.superproject.logininterceptor.LoginStatusUtil;
import com.study.zouchao.superproject.util.App;
import com.study.zouchao.superproject.util.EventBusEvent;
import com.study.zouchao.superproject.util.EventBusEvent_C;
import com.study.zouchao.superproject.util.EventBusUtils;
import com.study.zouchao.superproject.util.LogLongUtil;
import com.study.zouchao.superproject.util.ToastUtils;
import com.study.zouchao.superproject.util.api.MyRxManager;

import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/1/20.
 */

public class LoginPresenter implements ILoginContract.ILoginPresenter {
    private static final String TAG = "LoginP";
    private Context mContext;
    //V
    private ILoginContract.ILoginView mView;
    //M
    private ILoginContract.ILoginModel mModel;
    //RxManager
    private final MyRxManager myRxManager = new MyRxManager();

    private Subscription mSup = null;

    //登陆拦截信息
    private LoginCarrier mCarrier;

    public LoginPresenter(ILoginContract.ILoginView view, Context context, LoginCarrier carrier) {
        mView = view;
        mModel = new LoginModel();
        mContext = context;
        mCarrier = carrier;

    }

    /**
     * 尝试登陆
     * 包含判断登陆信息是否完整
     *
     * @param user
     * @param pwd
     */
    @Override
    public void attemptLogin(String user, String pwd) {
        boolean cancel = false;
        if (TextUtils.isEmpty(user)) {
            mView.setUsernameError(mContext.getString(R.string.error_username_required));
            cancel = true;
        } else if (!isValidUsername(user)) {
            mView.setUsernameError(mContext.getString(R.string.error_invalid_username));
            cancel = true;
        } else if (TextUtils.isEmpty(pwd)) {
            mView.setPwdError(mContext.getString(R.string.error_password_required));
            cancel = true;
        } else if (!isValidPwd(pwd)) {
            mView.setPwdError(mContext.getString(R.string.error_invalid_password));
            cancel = true;
        }
        //最后判断是否可以登陆
        if (!cancel) {
            //登陆操作
            doPostLogin(user, pwd);
        }
    }

    /**
     * TODO:判断用户名是否合法
     *
     * @param user
     * @return
     */
    private boolean isValidUsername(String user) {
        return true;
    }

    /**
     * TODO:判断密码是否合法
     *
     * @param pwd
     * @return
     */
    private boolean isValidPwd(String pwd) {
        return true;
    }

    /**
     * Post登陆
     *
     * @param username
     * @param password
     */
    private void doPostLogin(String user, String pwd) {
        //显示登陆进度条
        mView.showLogining(true);
//        /**
//         * 使用RxJava控制登陆状态
//         */
        mSup = mModel.login(getParams(user, pwd))
                .subscribe(new Action1<LoginResult>() {
                    @Override
                    public void call(LoginResult loginResult) {
                        loginSuccessAndjudgeLoginResult(loginResult);
                        //显示未登陆状态
                        mView.showLogining(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                        ToastUtils.showShort(App.getAppContext(), "登陆失败、");
                        //显示未登陆的状态
                        mView.showLogining(false);
                    }
                });
    }

    /**
     * 登陆成功后判断登陆结果
     *
     * @param loginResult
     */
    private void loginSuccessAndjudgeLoginResult(LoginResult loginResult) {
        LogLongUtil.logD("登陆result", loginResult.toString());
        switch (loginResult.getCode()) {
            case 21001:
                //保存用户信息
                saveLoginStatus(loginResult.getData());
                ToastUtils.showShort(mContext, "登陆成功!!");
                //登陆成功 跳转到对应的Activity
                loginSuccessAndGoto();
                break;
            default:
                ToastUtils.showShort(mContext, loginResult.getMessage());
                break;
        }
        Log.i("登陆结果", loginResult.getMessage());
    }

    /**
     * 登陆成功 跳转到对应的Activity
     */
    private void loginSuccessAndGoto() {
        if (mCarrier != null) {
            //跳转到登陆后的界面
            mCarrier.loginSuccessAndInvoke(mContext);
            //重置为空(不重置也行)
            mCarrier = null;
        }
        EventBusUtils.post(new EventBusEvent(EventBusEvent_C.EVENT_UPDATE_LOGIN_UI_IN_MAIN, null));
        //登陆成功后finish到当前登陆界面
        mView.finishCurrentLoginActivity();
    }

    /**
     * 登陆成功后保存
     * 保存登陆状态
     */
    private void saveLoginStatus(User user) {
        //保存用户信息
        LoginStatusUtil.saveLoginedUserInfo(mContext, user);
        //登陆成功 保留登陆状态
        LoginStatusUtil.saveLoginedStatus(mContext);
    }

    /**
     * 得到登陆参数
     *
     * @return
     */
    private Map<String, String> getParams(String user, String pwd) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", user);
        params.put("password", pwd);
        return params;
    }

    @Override
    public void onDestoryPresnter() {
        //取消登陆任务
        if (mSup != null && !mSup.isUnsubscribed()) {
            mSup.unsubscribe();
            ToastUtils.showShort(mContext, "取消登陆");
//            Log.d("onDestoryP", "取消绑定(取消登陆)");
        }
    }
}
